package com.antfin.exam.member.service;

import com.antfin.exam.member.feign.BonusRemoteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

@Service
public class MemberService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private BonusRemoteService remoteService;

    /**
     * 用户领用积分
     * @param userId 用户ID
     * @param bonusScoreId 积分池ID
     * @return
     */
    public int takeBonusScore(
            @PathVariable("userId") String userId
            ,@PathVariable("bonusScoreId") String bonusScoreId){

        //1.先通过redis读取user是否已经领抢过积分
        String logKey = String.format("log:%s-%s",userId,bonusScoreId);
        Object value = redisTemplate.opsForValue().get(logKey);
        if(value != null){
            throw new RuntimeException("用户"+userId+"已经领取过积分，请不要重复领取");
        }

        int score = calcUserScore(userId);

        //2.如果没有领抢过积分，通过微服务调用积分模块,获取积分
        return remoteService.takeBonusScore(userId,bonusScoreId,score);
    }

    /**
     * 计算用户可以抢的最大积分数，这里先mock为10
     * @param userId
     * @return
     */
    private int calcUserScore(String userId){
        return 10;
    }

}
